package com.qianfeng.missfood.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.qianfeng.missfood.BaseApp;
import com.qianfeng.missfood.R;
import com.qianfeng.missfood.constants.AppConfig;
import com.qianfeng.missfood.fragment.CategoryFragment;
import com.qianfeng.missfood.fragment.CookFragment;
import com.qianfeng.missfood.fragment.FoodFragment;
import com.qianfeng.missfood.fragment.MeFragment;
import com.qianfeng.missfood.utils.FragmentTabUtils;
import com.qianfeng.missfood.utils.LocationHelper;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private long exitTime = 0;
    @ViewInject(R.id.menuGroup)
    RadioGroup rg;
    private ArrayList<Fragment> fgs;
    private Bundle savedInstanceState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.savedInstanceState = savedInstanceState;
        ViewUtils.inject(this);
        fgs = new ArrayList<>();
        fgs.add(new FoodFragment());
        fgs.add(new CategoryFragment());
        fgs.add(new CookFragment());
        fgs.add(new MeFragment());
        new FragmentTabUtils(this, getSupportFragmentManager(), fgs, R.id.fragment_main_container, rg);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationHelper.getInstance().stop();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {

                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {

                finish();
                System.exit(0);

            }

            return true;
        }


        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (BaseApp.getInstance().getLoginState()) {

            if (requestCode == AppConfig.ME_REQUEST) {

                rg.getChildAt(rg.getChildCount() - 1).performClick();
            }

        }

    }
}
